//
//  CategoryPlayListViewController.m
//  JZMCFM
//
//  Created by MJL on 15/11/2.
//  Copyright (c) 2015年 陈卓. All rights reserved.
//

#import "CategoryPlayListViewController.h"
#import "ClassifyHelper.h"
#import "CategoryDetailCellModel.h"
#import "CategoryPlayListModel.h"
#import "PlayListTableViewCell.h"
#import "MJLPlayListHelper.h"
#import "PlayListModel.h"

#import "CategoryPlayViewController.h"

static NSString *cell_id = @"playCell";
@interface CategoryPlayListViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *PlayListTableView;
@property(nonatomic,strong)CategoryPlayListModel *listModel;
//存储播放列表头部的数据
@property(nonatomic,strong)NSMutableArray *listHeaderArray;
@property(nonatomic,strong)NSMutableArray *listArray;
@property(nonatomic,strong)UIImageView *btnImage1;
@property(nonatomic,strong)UILabel *btnLabel1;
@property(nonatomic,assign)BOOL isClick;
@property(nonatomic,assign)NSInteger indexCount;
@property(nonatomic,strong)CategoryDetailCellModel *model;
@end

@implementation CategoryPlayListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.model = self.cellDataArr[self.index];
    self.PlayListTableView.delegate = self;
    self.PlayListTableView.dataSource = self;
    

    [self downLoadPlayLisetDataWithString:[NSString stringWithFormat:@"%@%ld%@",PlayListCell1,self.model.ID,PlayListCell2]];
    
   //注册cell
    [self.PlayListTableView registerNib:[UINib nibWithNibName:@"PlayListTableViewCell" bundle:nil] forCellReuseIdentifier:cell_id];
    
    //调用解析
//     [[MJLPlayListHelper sharedInstance]downLoadPlayListDatawithString:[NSString stringWithFormat:@"%@%ld%@",PlayListCell3,self.model.ID,PlayListCell4] WithBlock:^{
//         
//         [self.PlayListTableView reloadData];
//     }];
    [self downLoadPlayListData];
    [self.PlayListTableView reloadData];
    
    [self UpdateDown];
}

#pragma amrk 解析播放列表头部
- (void)downLoadPlayLisetDataWithString:(NSString *)string{
    
    NSURL *strurl = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:strurl];
    [NSURLConnection  sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *albumDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dict =albumDict[@"album"];
        CategoryPlayListModel *model = [[CategoryPlayListModel alloc]init];
        [model setValuesForKeysWithDictionary:dict];
        [self.listHeaderArray addObject:model];
        self.listModel = model;
        [self.PlayListTableView reloadData];
    }];
    
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return [MJLPlayListHelper sharedInstance].playListArray.count;
    return self.listArray.count;
}

#pragma mark 自定义播放列表的头部
- (UIView *)setHeaderViewWithModel:(CategoryPlayListModel *)model
{
    
    CGFloat viewW = [UIScreen mainScreen].bounds.size.width;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewW, 180)];

    UIImageView *lagerImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
    [view addSubview:lagerImage];
    [lagerImage sd_setImageWithURL:[NSURL URLWithString:self.listModel.coverMiddle]];
    UIBlurEffect *beffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *lagerview = [[UIVisualEffectView alloc]initWithEffect:beffect];
    lagerview.frame = lagerImage.bounds;
    
    [lagerImage addSubview:lagerview];
    
    UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 20, 100, 100)];
    [leftImageView sd_setImageWithURL:[NSURL URLWithString:self.listModel.coverMiddle]];

    [view addSubview:leftImageView];
    //头像
    UIImageView *headerImage = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftImageView.frame) + 5, CGRectGetMinY(leftImageView.frame), 35, 35)];
    headerImage.layer.cornerRadius = 17.5;
    headerImage.clipsToBounds = YES;
    [headerImage sd_setImageWithURL:[NSURL URLWithString:self.listModel.avatarPath]];
    [view addSubview:headerImage];
    //昵称
    UILabel *nicknameLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headerImage.frame), CGRectGetMinY(headerImage.frame), 180, headerImage.frame.size.height)];
    nicknameLabel.text = self.listModel.nickname;
    [view addSubview:nicknameLabel];
    //简介
    UILabel *introLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(headerImage.frame), CGRectGetMaxY(headerImage.frame) + 5, nicknameLabel.frame.size.width + 50, 35)];
    introLabel.text = self.listModel.intro;

    introLabel.font = [UIFont systemFontOfSize:15.0];
    [view addSubview:introLabel];
    //类型
    UILabel *cateLabel = [[UILabel alloc]initWithFrame:CGRectMake(introLabel.frame.origin.x, CGRectGetMaxY(introLabel.frame) + 3, 230, 25)];
    cateLabel.text = self.listModel.tags;
    cateLabel.font = [UIFont systemFontOfSize:15.0];
//    cateLabel.textAlignment = NSTextAlignmentCenter;
//    cateLabel.layer.borderWidth = 1;
//    cateLabel.layer.cornerRadius = 10;
    [view addSubview:cateLabel];
    
    //收藏
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(CGRectGetMinX(leftImageView.frame)+10, CGRectGetMaxY(leftImageView.frame)+20, 90, 30);
    
    self.btnImage1= [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [button1 addSubview:self.btnImage1];
    self.btnImage1.image = [UIImage imageNamed:@"mjliconfont-shoucang"];
    self.btnLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.btnImage1.frame), 0, button1.frame.size.width - self.btnImage1.frame.size.width, 30)];
    self.btnLabel1.text = @"收藏";
    self.btnLabel1.font = [UIFont systemFontOfSize:15.0];
    self.btnLabel1.textAlignment = NSTextAlignmentCenter;
    [button1 addSubview:self.btnLabel1];
    [button1 addTarget:self action:@selector(btnCollection:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button1];
    
    //下载
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(CGRectGetMaxX(button1.frame)+40, CGRectGetMinY(button1.frame), 70, 30);
    
    UIImageView *btnImage2= [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [button2 addSubview:btnImage2];
    btnImage2.image = [UIImage imageNamed:@"mjliconfont-xiazai"];
    UILabel *btnlabel2 = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(btnImage2.frame), 0, button2.frame.size.width - btnImage2.frame.size.width, 30)];
    btnlabel2.text = @"下载";
    btnlabel2.font = [UIFont systemFontOfSize:15.0];
    btnlabel2.textAlignment = NSTextAlignmentCenter;
    [button2 addSubview:btnlabel2];
    [button2 addTarget:self action:@selector(downLoadBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button2];
    
    //相关推荐
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake(CGRectGetMaxX(button2.frame)+40, CGRectGetMinY(button2.frame), 70, 30);
    
    UIImageView *btnImage3= [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [button3 addSubview:btnImage3];
    btnImage3.image = [UIImage imageNamed:@"mjliconfont-xiangguanshangpin"];
    UILabel *btnlabel3 = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(btnImage3.frame), 0, button3.frame.size.width - btnImage3.frame.size.width, 30)];
    btnlabel3.text = @"推荐";
    btnlabel3.textAlignment = NSTextAlignmentCenter;
    btnlabel3.font = [UIFont systemFontOfSize:15.0];
    [button3 addSubview:btnlabel3];
    [button3 addTarget:self action:@selector(tuijianBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button3];

    
    return view;
    
}

- (void)downLoadPlayListData
{
   
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%ld/true/%ld/20?albumId=350700&isAsc=true&device=android&pageSize=20",PlayListCell3,self.model.ID,self.indexCount]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *tracksDict = dict[@"tracks"];
            NSArray *listArray = tracksDict[@"list"];
            for (NSDictionary *dict in listArray) {
                PlayListModel *model = [[PlayListModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [self.listArray addObject:model];
                [self.PlayListTableView reloadData];
            }
        }];
        
        

    
    
}


#pragma mark 下拉刷新
- (void)UpdateDown
{
    self.indexCount = 1;
    self.PlayListTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.indexCount ++;
        //调用解析
        [self downLoadPlayListData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.PlayListTableView.footer endRefreshing];
        });

    }];
}

#pragma mark 代理事件
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  return   [self setHeaderViewWithModel:self.listModel];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 180;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id forIndexPath:indexPath];
//    PlayListModel *model = [MJLPlayListHelper sharedInstance].playListArray[indexPath.row];
    PlayListModel *model = self.listArray[indexPath.row];
    [cell setCellDataWithModel:model];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 72;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CategoryPlayViewController *playVC = [CategoryPlayViewController sharedInstance];
    playVC.index = indexPath.row;
    playVC.playListArray = self.listArray;
    playVC.playListHeaderArray = self.listHeaderArray;
    playVC.listHeaderModel = self.listModel;
    playVC.copyID = self.model.ID;
    [self.navigationController pushViewController:playVC animated:YES];
}


#pragma mark Button的点击事件

- (void)btnCollection:(UIButton *)sender
{
    self.isClick = !self.isClick;
    if (self.isClick == 1) {
        self.btnImage1.image = [UIImage imageNamed:@"mjliconfont-shoucang(1)"];
        self.btnLabel1.text = @"已收藏";
    }else{
        self.btnImage1.image = [UIImage imageNamed:@"mjliconfont-shoucang"];
        self.btnLabel1.text = @"收藏";
    }
}

- (void)downLoadBtn:(UIButton *)sender
{
    NSLog(@"点击了下载按钮");
}

- (void)tuijianBtn:(UIButton *)sender
{
    NSLog(@"点击了推荐按钮");
}

- (NSMutableArray *)listHeaderArray
{
    if (!_listHeaderArray) {
        _listHeaderArray = [NSMutableArray array];
    }
    return _listHeaderArray;
}

- (NSMutableArray *)listArray
{
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
